package com.db;
import java.sql.*;

public class DatabaseConnector {

    private Connection connection; // 数据库连接对象

    private String url = "jdbc:mysql://127.0.0.1:9906/lianxi?useSSL=true"; // 数据库URL
    // 数据库用户名
    private String user = "root";
    // 数据库密码
    private String password = "sa";

//    private String url = "jdbc:mysql://localhost:3306/lianxi"; // 数据库URL
//    private String user = "root"; // 数据库用户名
//    private String password = "123456"; // 数据库密码
    public Connection getDBConnection(){
        try {
            connection = DriverManager.getConnection(url, user, password);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        return connection;
    }
    // 构造函数，初始化数据库连接参数
    public DatabaseConnector() {

    }
    // 构造函数，初始化数据库连接参数
    public DatabaseConnector(String url, String user, String password) {
        this.url = url;
        this.user = user;
        this.password = password;
    }

    // 连接到数据库
    public void connect() throws SQLException {
        connection = DriverManager.getConnection(url, user, password);
    }

    // 获取数据库连接
    public Connection getConnection() {
        return connection;
    }

    // 关闭数据库连接
    public void close() throws SQLException {
        if (connection != null && !connection.isClosed()) {
            connection.close(); // 关闭连接
        }
    }
    public static void closeDB(ResultSet rs, PreparedStatement ps, Connection connection) {

        try {
            if (rs != null) {
                rs.close();
            }
            if (ps != null) {
                ps.close();
            }
            if (connection != null) {
                connection.close();
            }
        } catch (SQLException ex) {
            // 适当处理异常
            ex.printStackTrace();
        }
    }
}

